package main

import (
	"bufio"
	"dnspod"
	"fmt"
	"os"
	"regexp"
	"strings"
)

var cli *dnspod.Client

// LoadConf load config
func LoadConf(dir string) {
	f, err := os.Open(dir)
	assert(err)
	defer f.Close()
	s := bufio.NewScanner(f)
	reg := regexp.MustCompile("#.+$")

	var ctx struct {
		id    string
		token string
	}

	for s.Scan() {
		row := strings.TrimSpace(s.Text())
		row = strings.TrimSpace(reg.ReplaceAllString(row, ""))
		if len(row) == 0 {
			continue
		}
		kv := strings.SplitN(row, "=", 2)
		if len(kv) != 2 {
			fmt.Printf("Invalid row in config: %s\n", row)
			continue
		}
		k, v := strings.TrimSpace(kv[0]), strings.TrimSpace(kv[1])
		switch k {
		case "id":
			ctx.id = v
		case "token":
			ctx.token = v
		}
	}

	if len(ctx.id) == 0 {
		fmt.Println("Missing id in config file")
		os.Exit(1)
	}
	if len(ctx.token) == 0 {
		fmt.Println("Missing token in config file")
		os.Exit(1)
	}

	cli = dnspod.NewClient(ctx.id, ctx.token)
}
